#include <QtXml>
#include "JDomItem.h"

JDomItem::JDomItem(QDomNode &node, int row, JDomItem *parent)
{
    domNode = node;
    // Record the item's location within its parent.
    rowNumber = row;
    parentItem = parent;
}

JDomItem::~JDomItem()
{
    QHash<int,JDomItem*>::iterator it;
    for (it = childItems.begin(); it != childItems.end(); ++it)
        delete it.value();
	//qDeleteAll(childItems);
}

QDomNode JDomItem::node() const
{
    return domNode;
}

JDomItem *JDomItem::parent()
{
    return parentItem;
}

JDomItem *JDomItem::child(int i)
{
    if (childItems.contains(i))
        return childItems[i];

	//return childItems.value(i);

    if (i >= 0 && i < domNode.childNodes().count()) {
        QDomNode childNode = domNode.childNodes().item(i);
        JDomItem *childItem = new JDomItem(childNode, i, this);
        childItems[i] = childItem;
		//childItems.value(i) = childItem;
        return childItem;
    }
    return 0;
}

int JDomItem::row()
{
    return rowNumber;
}

QVariant JDomItem::data( int column ) const
{
	return itemData.value(column);
}

bool JDomItem::setData( int column, const QVariant &value )
{
	if (column < 0 || column >= itemData.size())
		return false;

	itemData[column] = value;
	return true;
}

bool JDomItem::insertChildren( int position, int count, int columns )
{
	if (position < 0 || position > domNode.childNodes().count())
		return false;

	for (int row = 0; row < count; ++row) {
		/*QVector<QVariant> data(columns);
		JDomItem *item = new JDomItem(data, this);
		childItems.insert(position, item);*/
		QDomNode childNode = domNode.childNodes().item(position);
		JDomItem *childItem = new JDomItem(childNode, position, this);
		childItems[position] = childItem;
	}

	return true;
}

bool JDomItem::removeChildren( int position, int count )
{
	if (position < 0 || position + count > domNode.childNodes().count())
		return false;

	for (int row = 0; row < count; ++row)
		//delete childItems.takeAt(position);
		delete childItems[position];

	return true;
}

int JDomItem::childCount() const
{
	return domNode.childNodes().count();
}

//int JDomItem::childNumber() const
//{
//	if (parentItem)
//		return parentItem->childItems.indexOf(const_cast<JDomItem*>(this));
//
//	return 0;
//}